#include "oiltanks.h"
#include <cassert>

namespace cores
{
    namespace devices
    {
        OilTanksManager *OilTanksManager::globalInstance{nullptr};

        OilTanksManager::OilTanksManager()
        {
            if (OilTanksManager::globalInstance == nullptr)
                OilTanksManager::globalInstance = this;
        }

        OilTanksManager::~OilTanksManager()
        {
            if (OilTanksManager::globalInstance == this)
                OilTanksManager::globalInstance = nullptr;
        }

        int OilTanksManager::Count()
        {
            assert(OilTanksManager::globalInstance);
            return OilTanksManager::globalInstance->count();
        }

        OilTanksReq *OilTanksManager::Get(const uint8_t &code)
        {
            assert(OilTanksManager::globalInstance);
            return OilTanksManager::globalInstance->get(code);
        }

        void OilTanksManager::Add(const OilTanksReq &tank)
        {
            assert(OilTanksManager::globalInstance);

            auto tmp = shared_ptr<OilTanksReq>(new OilTanksReq);
            tmp->code = tank.code;
            tmp->category = tank.category;
            tmp->tank_address = tank.tank_address;
            tmp->has_data = tank.has_data;
            tmp->is_answer = tank.is_answer;
            tmp->no_answer_count = tank.no_answer_count;
            tmp->error_count = tank.error_count;
            OilTanksManager::globalInstance->add(tmp);
        }

        void OilTanksManager::Add(const OilTanksReq *tank)
        {
            assert(OilTanksManager::globalInstance);

            auto tmp = shared_ptr<OilTanksReq>(new OilTanksReq);
            tmp->code = tank->code;
            tmp->category = tank->category;
            tmp->tank_address = tank->tank_address;
            tmp->has_data = tank->has_data;
            tmp->is_answer = tank->is_answer;
            tmp->no_answer_count = tank->no_answer_count;
            tmp->error_count = tank->error_count;
            OilTanksManager::globalInstance->add(tmp);
        }

        void OilTanksManager::Clear()
        {
            assert(OilTanksManager::globalInstance);
            OilTanksManager::globalInstance->clear();
        }

        int OilTanksManager::count()
        {
            return _tanks.size();
        }

        OilTanksReq *OilTanksManager::get(const uint8_t &code)
        {
            if (_tanks.count(code) == 0)
                return 0;

            return _tanks[code].get();
        }

        void OilTanksManager::add(shared_ptr<OilTanksReq> tank)
        {
            if (tank.get() == nullptr)
                return;

            _tanks[tank->code] = tank;
        }

        void OilTanksManager::clear()
        {
            _tanks.clear();
        }
    }
}